package com.szrt.java.day20170113.demo10.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 动态代理
 * @author zsrt
 *
 */
public class StudentDaoProxy implements InvocationHandler{

	private Object obj;

	
	public StudentDaoProxy() {
		
	}
	public StudentDaoProxy(Object obj) {
		this.obj = obj;
	}
	
	/**
	 * 当我们调用getProxyInstance 方法的时候，因为我们这个类实现InvocationHandler
	 * 
	 * ==> 结论：jvm会自动回调invoke
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public Object getProxyInstance(){
		
		ClassLoader loader = obj.getClass().getClassLoader();
		Class[] interfaces = obj.getClass().getInterfaces();
		
		Object object = Proxy.newProxyInstance(loader, interfaces, this);
		
		return object;
	}
	
	/**
	 * 一统江山
	 */
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		
		System.out.println("在方法执行之前开启事务...");
		Object returnValue = method.invoke(obj, args);
		System.out.println("在方法执行之后提交事务...");
		return returnValue;
	}
	
	
	
}
